import { Injectable, NotFoundException, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  // 模拟用户数据（实际项目中应从数据库获取）
  private readonly users = [
    { id: 1, username: 'testuser', password: '$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW' }, // 密码为 'password'
  ];

  // 注册用户
  async register(username: string, password: string) {
    const hashedPassword = await bcrypt.hash(password, 10); // 加密密码
    console.log(hashedPassword);
    const newUser = { id: this.users.length + 1, username, password: hashedPassword };
    this.users.push(newUser);
    return { message: '用户注册成功', user: { id: newUser.id, username: newUser.username } };
  }

  // 登录用户并生成 Token
  async login(username: string, password: string):Promise<string>{
    const user = this.users.find((u) => u.username === username);
    // 检查用户是否存在
    if (!user) {
      throw new NotFoundException('用户未找到');
    }

    // 验证密码
    const isPasswordValid = await bcrypt.compare(password, user.password);

    // if (!isPasswordValid) {
    //   throw new UnauthorizedException('密码错误');
    // }
    // 生成 JWT Token
    const payload = { sub: user.id, username: user.username }; // Payload 数据
    console.log(payload);
    const token = this.jwtService.sign(payload); // 签发 Token
    console.log(token);
    return  token  ;
  }
}